import random

import matplotlib.pyplot as plt
from keras.datasets.cifar10 import load_data
from keras import Sequential, layers, activations, optimizers, losses, Model
import numpy as np
import tensorflow as tf

(x_train, y_train), (x_test, y_test) = load_data()
x_train = x_train/ 255
x_test = x_test / 255

onehot_dim = 10


class Lenet5(Model):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.conv = Sequential([
            layers.Conv2D(filters=6, kernel_size=(5, 5), activation=activations.relu),
            layers.MaxPooling2D(),
            layers.Conv2D(filters=16, kernel_size=(5, 5), activation=activations.relu),
            layers.MaxPooling2D(),
        ])
        self.flat = layers.Flatten()
        self.fc = Sequential([
            layers.Dense(units=120, activation=activations.relu),
            layers.Dense(units=84, activation=activations.relu),
            layers.Dense(units=onehot_dim, activation=activations.softmax)
        ])

    def call(self, inputs, training=None, mask=None):
        out = self.conv(inputs)
        out = self.flat(out)
        out = self.fc(out)
        return out


model = Lenet5()
model.build(input_shape=(None, 32, 32, 3))
model.summary()
model.compile(optimizer=optimizers.Adam(), loss=losses.sparse_categorical_crossentropy, metrics='acc')

log = model.fit(x_train, y_train, epochs=10, batch_size=100, validation_data=(x_test, y_test))

train_acc = log.history['acc']
val_acc = log.history['val_acc']
plt.plot(train_acc, color='r')
plt.plot(val_acc, color='g')
plt.show()

index = random.randint(0, len(x_test) - 1)
predicted_labels = np.argmax(model.predict(x_test[index:index + 1]))
cifar10_labels = {
                    0: 'airplane（飞机）',
                    1: 'automobile（汽车）',
                    2: 'bird（鸟）',
                    3: 'cat（猫）',
                    4: 'deer（鹿）',
                    5: 'dog（狗）',
                    6: 'frog（青蛙）',
                    7: 'horse（马）',
                    8: 'ship（船）',
                    9: 'truck（卡车）'
                }
plt.imshow(tf.squeeze(x_test[index]), cmap='gray')
plt.title(f'predict val:{cifar10_labels[predicted_labels]}')
plt.show()
